package com.nbsaas.boot.handle;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.Hashtable;
import java.util.Map;

public class TalkHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {


    public static ChannelGroup users = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    public static Map<String, String> channels = new Hashtable<>();

    public static Map<String, String> devices = new Hashtable<>();


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) {
        // 处理接收到的WebSocket文本帧
        String receivedMessage = msg.text();

        ctx.channel().writeAndFlush(new TextWebSocketFrame(receivedMessage));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // 发生异常时的处理逻辑
        cause.printStackTrace();
        ctx.close();
        //users.remove(ctx.channel());

    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        System.out.println("接收到了一个客户端的连接请求啦，当前的连接用户的channel的短ID是:" + ctx.channel().id().asShortText());
        users.add(ctx.channel());
        String shortId=ctx.channel().id().asShortText();

    }
}
